package com.demo.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * 
 */
@ConditionalOnProperty(prefix = "web.valid", value = "simple", havingValue = "true", matchIfMissing = false)
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {


 
    /**
     * <pre>
     * 用于方法中平铺的参数校验适用于任意的类
     * 上使用@Validated标注，
     * 
     * 然后方法上正常使用约束注解标注平铺的属性 javax.validation.ConstraintViolationException
     * 这是Spring自带的针对方法校验的
     * 方式一
     * @Bean
     * Springboot自动导入会将Controller层生形成代理
     * </pre>
     * 
     * @return
     */

     public MethodValidationPostProcessor mvcMethodValidationPostProcessor() {
        return new MethodValidationPostProcessor();
    }

    // 自己配置校验器的工厂 自己随意定制化哦~,Springboot自动导入
//    @Bean
    public LocalValidatorFactoryBean localValidatorFactoryBean() {
        // validator.setValidationMessageSource(this.messageSource());//支持国际化的错误信息
        // validator.setProviderClass（HibernateValidator.class）;//指定验证器实现的提供方
        return new LocalValidatorFactoryBean();
    }

    // 配置用于校验的拦截器
    @Bean
    public ValidationInterceptor validationInterceptor() {
        return new ValidationInterceptor();
    }
    /**
     * 方式二
     * 
     * @return
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(validationInterceptor()).addPathPatterns("/**");
    }
}
